package cn.dankal.flyaudio.personal;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.classic.common.MultipleStatusView;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.jyj.recruitment.wxapi.WxConstants;
import com.kongzue.dialog.v2.SelectDialog;

import java.util.List;

import androidx.lifecycle.Observer;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cn.dankal.basiclib.base.activity.BaseActivity;
import cn.dankal.basiclib.base.recyclerview.OnRvItemClickListener;
import cn.dankal.basiclib.pojo.CreateOrderPreviewEntity;
import cn.dankal.basiclib.util.ActivityUtils;
import cn.dankal.flyaudio.R;
import cn.dankal.flyaudio.adapter.OrderAdapter;
import cn.dankal.flyaudio.configs.OrderPagerConfigs;
import cn.dankal.flyaudio.configs.PayConfigs;
import cn.dankal.flyaudio.contract.MyOrderContract;
import cn.dankal.flyaudio.pop.PayMethodPop;
import cn.dankal.flyaudio.presenter.MyOrderPresenter;
import cn.dankal.flyaudio.store.PayResultActivity;
import razerdp.basepopup.BasePopupWindow;

import static com.jyj.recruitment.wxapi.WxConstants.PAY_FAILED;
import static com.jyj.recruitment.wxapi.WxConstants.PAY_SUCCESS;

public class MyOrderActivity extends BaseActivity implements View.OnClickListener, MyOrderContract.View {

    public static final String WAITING_PAY = "WAITING_PAY";
    public static final String WAITING_COMMENT = "WAITING_COMMENT";
    public static final String SUCCESS = "SUCCESS";
    public static final String CLOSE = "CLOSED";
    public static final String AFTER_SALE = "AFTER_SALE";
    public static final String USER_CANCELLED = "USER_CANCELLED";
    public static final String TIMEOUT_CANCELLED = "TIMEOUT_CANCELLED";//超时取消

    public static final String WAITING = "WAITING";//申请中
    public static final String REJECTED = "REJECTED";//已拒绝
    public static final String WAITING_SHIP = "WAITING_SHIP";//商家已同意, 等待用户发货
    public static final String SHIPPING = "SHIPPING";//商家已同意, 等待收货
    public static final String WAITING_REFUND = "WAITING_REFUND";//商家已收货, 退款中
    public static final String REFUND_SUCCESS = "REFUND_SUCCESS";//退款成功, 订单关闭

    private View allView;
    private View paymentView;
    private View sendStoreView;
    private View collectionStoreView;
    private View evaluateView;
    private RecyclerView orderListView;
    private List<CreateOrderPreviewEntity> orderBeans;
    private OrderAdapter orderAdapter;
    private MyOrderPresenter myOrderPresenter;
    private PayReceive receive = new PayReceive();
    private MultipleStatusView statusView;

    private CreateOrderPreviewEntity mCreateOrderPreviewEntity;

    private int pageType = OrderPagerConfigs.PAGE_TYPE_ALL;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_my_order;
    }

    @Override
    public void initComponents() {
        addSingleTitleBar("我的订单");
        myOrderPresenter = new MyOrderPresenter();
        myOrderPresenter.attachView(this);
        statusView = findViewById(R.id.multiple_status_view);
        initView();
        pageType = getIntent().getIntExtra("order_type", OrderPagerConfigs.PAGE_TYPE_ALL);
        initPage();
        orderListView.setLayoutManager(new LinearLayoutManager(this));
        orderAdapter = new OrderAdapter();
        orderAdapter.setOnButtonClickListener(new OrderAdapter.OnButtonClickListener() {
            @Override
            public void doPay(CreateOrderPreviewEntity createOrderPreviewEntity) {
                mCreateOrderPreviewEntity = createOrderPreviewEntity;
                PayMethodPop payMethodPop = new PayMethodPop(MyOrderActivity.this);
                payMethodPop.setOnDismissListener(new BasePopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        int payMethod = payMethodPop.getPayMethod();
                        if (payMethod == PayConfigs.PAY_METHOD_ALIPAY) {
                            myOrderPresenter.alipay(createOrderPreviewEntity.getUuid());
                            return;
                        }
                        if (payMethod == PayConfigs.PAY_METHOD_WECHAT) {
                            myOrderPresenter.wechatPay(createOrderPreviewEntity.getUuid());
                        }
                    }
                });
                payMethodPop.showPopupWindow(findViewById(android.R.id.content));

            }

            @Override
            public void confirmReceive(CreateOrderPreviewEntity createOrderPreviewEntity) {
                SelectDialog.show(MyOrderActivity.this, "提示", "确认是否已收到货物", "确定", (dialog, which) -> {
                    myOrderPresenter.confirmReceiveStore(createOrderPreviewEntity.getUuid());
                }, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
            }

            @Override
            public void toComment(CreateOrderPreviewEntity createOrderPreviewEntity) {
                Bundle bundle = new Bundle();
                bundle.putString("id", createOrderPreviewEntity.getUuid());
                if(createOrderPreviewEntity.getOrderItemList().size()>0) {

                    bundle.putString("model",
                            JSON.toJSONString(createOrderPreviewEntity.getOrderItemList()));
                }
                ActivityUtils.startActivity(bundle, MyCommentActivity.class);
            }
        });


        orderListView.setAdapter(orderAdapter);
//        orderAdapter.addDatas(orderBeans,true);
        orderAdapter.setOnRvItemClickListener(new OnRvItemClickListener<CreateOrderPreviewEntity>() {
            @Override
            public void onItemClick(View v, int position, CreateOrderPreviewEntity data) {
                Intent intent = new Intent(MyOrderActivity.this, MyOrderDetailActivity.class);
                intent.putExtra("orderUuid", data.getUuid());
                startActivity(intent);
            }
        });
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(PAY_FAILED);
        intentFilter.addAction(PAY_SUCCESS);
        LocalBroadcastManager.getInstance(this).registerReceiver(receive, intentFilter);
    }

    private void initPage() {
        if (pageType == OrderPagerConfigs.PAGE_TYPE_ALL) {
            showAllOrderLayout();
        } else if (pageType == OrderPagerConfigs.PAGE_TYPE_PAYMENT) {
            showPaymentOrderLayout();
        } else if (pageType == OrderPagerConfigs.PAGE_TYPE_SEND_STORE) {
            showSendStoreLayout();
        } else if (pageType == OrderPagerConfigs.PAGE_TYPE_COLLECTION_STORE) {
            showCollectionStoreLayout();
        } else if (pageType == OrderPagerConfigs.PAGE_TYPE_EVALUATE) {
            showEvaluateViewLayout();
        } else {
            showAllOrderLayout();
        }
    }

    private void initView() {
        allView = findViewById(R.id.rl_all);
        paymentView = findViewById(R.id.rl_payment);
        sendStoreView = findViewById(R.id.rl_send_store);
        collectionStoreView = findViewById(R.id.rl_collection_store);
        evaluateView = findViewById(R.id.rl_evaluate);
        orderListView = findViewById(R.id.swipe_target);
        allView.setOnClickListener(this);
        paymentView.setOnClickListener(this);
        sendStoreView.setOnClickListener(this);
        collectionStoreView.setOnClickListener(this);
        evaluateView.setOnClickListener(this);

        LiveEventBus.get("RefreshOrder", String.class).observe(
                this, new Observer<String>() {
                    @Override
                    public void onChanged(String s) {
                        myOrderPresenter.getMyOrder("-1", true);
                    }
                }
        );
    }

    private void showAllOrderLayout() {
        allView.setSelected(true);
        paymentView.setSelected(false);
        sendStoreView.setSelected(false);
        collectionStoreView.setSelected(false);
        evaluateView.setSelected(false);
        myOrderPresenter.getMyOrder("", true);
    }

    private void showPaymentOrderLayout() {
        allView.setSelected(false);
        paymentView.setSelected(true);
        sendStoreView.setSelected(false);
        collectionStoreView.setSelected(false);
        evaluateView.setSelected(false);
        myOrderPresenter.getMyOrder(WAITING_PAY, true);
    }

    private void showSendStoreLayout() {
        allView.setSelected(false);
        paymentView.setSelected(false);
        sendStoreView.setSelected(true);
        collectionStoreView.setSelected(false);
        evaluateView.setSelected(false);
        myOrderPresenter.getMyOrder(WAITING_SHIP, true);
    }

    private void showCollectionStoreLayout() {
        allView.setSelected(false);
        paymentView.setSelected(false);
        sendStoreView.setSelected(false);
        collectionStoreView.setSelected(true);
        evaluateView.setSelected(false);
        myOrderPresenter.getMyOrder(SHIPPING, true);
    }

    private void showEvaluateViewLayout() {
        allView.setSelected(false);
        paymentView.setSelected(false);
        sendStoreView.setSelected(false);
        collectionStoreView.setSelected(false);
        evaluateView.setSelected(true);
        myOrderPresenter.getMyOrder(WAITING_COMMENT, true);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(receive);
        myOrderPresenter.detachView();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (R.id.rl_all == id) {
            showAllOrderLayout();
        } else if (R.id.rl_payment == id) {
            showPaymentOrderLayout();
        } else if (R.id.rl_send_store == id) {
            showSendStoreLayout();
        } else if (R.id.rl_collection_store == id) {
            showCollectionStoreLayout();
        } else if (R.id.rl_evaluate == id) {
            showEvaluateViewLayout();
        }
    }

    @Override
    public void showOrderList(List<CreateOrderPreviewEntity> datas, boolean isRefresh) {
        if (datas.isEmpty() && isRefresh) {
            orderAdapter.clearData();
            statusView.showEmpty();
            return;
        }
        statusView.showContent();
        orderAdapter.addDatas(datas, isRefresh);
    }

    @Override
    public void showDialog(String content) {

    }

    class PayReceive extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (TextUtils.equals(intent.getAction(), WxConstants.PAY_SUCCESS)) {
                Intent jump = new Intent(ActivityUtils.getTopActivity(), PayResultActivity.class);
                jump.putExtra("isPaySuccess", true);
                jump.putExtra("orderUuid", mCreateOrderPreviewEntity.getUuid());
                ActivityUtils.startActivity(jump);
                finish();

            } else if (TextUtils.equals(intent.getAction(), PAY_FAILED)) {
                Intent jump = new Intent(ActivityUtils.getTopActivity(), PayResultActivity.class);
                jump.putExtra("isPaySuccess", false);
                jump.putExtra("orderUuid", mCreateOrderPreviewEntity.getUuid());
                ActivityUtils.startActivity(jump);
                finish();
            }
        }
    }
}
